import { defineStore } from 'pinia'
import { getGoodsList } from '@/api/goods2'

export const useShopcartStore = defineStore('shopcart', {
  state: () => ({
    goodsList: [],
    cartList: [],
  }),
  getters: {
    total() {
      let sum = 0
      this.cartList.forEach((item) => {
        sum += item.price * item.num
      })
      return sum
    },
  },
  actions: {
    async initGoodsList() {
      const res = await getGoodsList(2)
      this.goodsList = res.data
    },
    addCart(goods) {
      //1.判断本次加入到商品,是否在购物车中,如果在,数量加1,不在,加入购物车,数量置1
      const index = this.cartList.findIndex((item) => item.id == goods.id)
      if (index >= 0) {
        //existed
        this.cartList[index].num++
      } else {
        //no existed
        this.cartList.push({
          id: goods.id,
          name: goods.name,
          sell_point: goods.sell_point,
          price: goods.price,
          image: goods.image,
          num: 1,
        })
      }
    },
    addNum(goods) {
      const index = this.cartList.findIndex((item) => item.id == goods.id)
      this.cartList[index].num++
    },
    subNum(goods) {
      const index = this.cartList.findIndex((item) => item.id == goods.id)
      this.cartList[index].num--
    },
  },
})
